// pages/auth/auth.ts
import { AuthAPI } from '../../utils/api'

interface AuthPageData {
  isLoggedIn: boolean;
  showRegister: boolean;
  showPhoneLogin: boolean;
  showMerchantApply: boolean;
  userInfo: any;
  loading: boolean;
  
  // 手机号登录
  loginPhone: string;
  password: string;
  showPassword: boolean;
  rememberPassword: boolean;
  loginMode: 'password' | 'sms';  // 登录模式：密码登录或验证码登录
  loginSmsCode: string;  // 登录验证码
  loginSmsCountdown: number;  // 登录验证码倒计时
  
  // 注册表单
  registerPhone: string;
  smsCode: string;
  registerPassword: string;
  confirmPassword: string;
  showRegisterPassword: boolean;
  smsCountdown: number;
  agreeProtocol: boolean;
  
  // 商家入驻申请
  merchantName: string;
  merchantType: number;
  merchantTypes: string[];
  contactPerson: string;
  contactPhone: string;
  merchantAddress: string;
  description: string;
}

Page({
  data: {
    isLoggedIn: false,
    showRegister: false,
    showPhoneLogin: false,
    showMerchantApply: false,
    userInfo: null,
    loading: false,
    
    // 手机号登录
    loginPhone: '',
    password: '',
    showPassword: false,
    rememberPassword: false,
    loginMode: 'password',  // 默认密码登录
    loginSmsCode: '',
    loginSmsCountdown: 0,
    
    // 注册表单
    registerPhone: '',
    smsCode: '',
    registerPassword: '',
    confirmPassword: '',
    showRegisterPassword: false,
    smsCountdown: 0,
    agreeProtocol: false,
    
    
    // 商家入驻申请
    merchantName: '',
    merchantType: -1,
    merchantTypes: ['个体工商户', '企业'],
    contactPerson: '',
    contactPhone: '',
    merchantAddress: '',
    description: ''
  } as AuthPageData,

  onLoad() {
    // 检查是否已经登录
    this.checkLoginStatus();
    // 读取保存的账号密码
    this.loadRememberedCredentials();
  },

  /**
   * 检查登录状态
   * 如果已登录则直接跳转到主页面
   */
  checkLoginStatus() {
    const token = wx.getStorageSync('merchantToken');
    const userInfo = wx.getStorageSync('merchantUserInfo');
    
    if (token && userInfo) {
      this.setData({
        isLoggedIn: true
      });
      // 跳转到工作台页面
      wx.switchTab({
        url: '/pages/workplace/workplace'
      });
    }
  },

  /**
   * 读取保存的账号密码
   */
  loadRememberedCredentials() {
    const rememberPassword = wx.getStorageSync('rememberPassword');
    if (rememberPassword) {
      const savedPhone = wx.getStorageSync('savedPhone');
      const savedPassword = wx.getStorageSync('savedPassword');
      if (savedPhone && savedPassword) {
        this.setData({
          loginPhone: savedPhone,
          password: savedPassword,
          rememberPassword: true
        });
      }
    }
  },

  // 显示手机号登录表单
  showPhoneLoginForm() {
    this.setData({
      showPhoneLogin: true
    });
  },

  // 显示注册表单
  showRegisterForm() {
    this.setData({
      showRegister: true,
      showPhoneLogin: false
    });
  },

  // 显示商家入驻申请表单
  showMerchantApplyForm() {
    this.setData({
      showMerchantApply: true
    });
  },

  // 显示忘记密码表单（跳转到新页面）
  showForgotPassword() {
    wx.navigateTo({
      url: '/pages/auth/forgot-password?phone=' + this.data.loginPhone
    });
  },

  // 返回主界面
  backToMain() {
    this.setData({
      showPhoneLogin: false,
      showMerchantApply: false
    });
  },

  // 返回手机登录界面
  backToPhoneLogin() {
    this.setData({
      showRegister: false,
      showPhoneLogin: true
    });
  },

  // 切换到登录
  switchToLogin() {
    this.setData({
      showRegister: false
    });
  },

  // 切换到注册
  switchToRegister() {
    this.setData({
      showRegister: true
    });
  },

  // 切换登录模式（密码登录/验证码登录）
  switchLoginMode() {
    this.setData({
      loginMode: this.data.loginMode === 'password' ? 'sms' : 'password'
    });
  },

  /**
   * 手机号登录（支持密码登录和验证码登录）
   */
  async handlePhoneLogin() {
    const { loginPhone, password, loginMode, loginSmsCode } = this.data;
    
    if (!this.validatePhone(loginPhone)) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      });
      return;
    }
    
    // 密码登录验证
    if (loginMode === 'password') {
      if (!password.trim()) {
        wx.showToast({
          title: '请输入密码',
          icon: 'none'
        });
        return;
      }
    } 
    // 验证码登录验证
    else if (loginMode === 'sms') {
      if (!loginSmsCode.trim()) {
        wx.showToast({
          title: '请输入验证码',
          icon: 'none'
        });
        return;
      }
    }

    this.setData({ loading: true });

    try {
      // 根据登录模式调用不同的API
      let response;
      if (loginMode === 'password') {
        response = await AuthAPI.merchantLogin({
          phone: loginPhone,
          password: password,
          loginType: 'password'
        });
      } else {
        response = await AuthAPI.merchantSmsLogin({
          phone: loginPhone,
          smsCode: loginSmsCode,
          loginType: 'sms'
        });
      }
      
      // 处理登录成功响应
      if (response.code === 200) {
        // 保存token（后端返回的token在response.token中）
        wx.setStorageSync('merchantToken', response.token);
        
        // 保存商家信息
        if (response.merchantInfo) {
          wx.setStorageSync('merchantUserInfo', response.merchantInfo);
        }
        
        // 处理记住密码
        if (this.data.rememberPassword) {
          wx.setStorageSync('rememberPassword', true);
          wx.setStorageSync('savedPhone', loginPhone);
          wx.setStorageSync('savedPassword', password);
        } else {
          wx.removeStorageSync('rememberPassword');
          wx.removeStorageSync('savedPhone');
          wx.removeStorageSync('savedPassword');
        }

        // 获取商家信息和审核状态
        const merchantInfo = response.merchantInfo;
        const auditStatus = merchantInfo?.auditStatus || merchantInfo?.externField1;

        console.log('登录成功，审核状态:', auditStatus);

        // 根据审核状态跳转到不同页面
        if (auditStatus === 'PENDING_INFO') {
          // 待完善信息 → 跳转入驻申请页面
          wx.showToast({
            title: '请先完善入驻信息',
            icon: 'none',
            duration: 2000
          });
          
          setTimeout(() => {
            wx.redirectTo({
              url: '/pages/settle/settle'
            });
          }, 2000);
        } 
        else if (auditStatus === 'UNDER_REVIEW') {
          // 审核中 → 跳转审核状态页面
          wx.showModal({
            title: '入驻申请审核中',
            content: '您的入驻申请正在审核中，预计1-3个工作日内完成审核。',
            showCancel: false,
            confirmText: '知道了',
            success: () => {
              wx.redirectTo({
                url: '/pages/audit-status/audit-status'
              });
            }
          });
        }
        else if (auditStatus === 'APPROVED') {
          // 审核通过 → 跳转商家工作台
          wx.showToast({
            title: '登录成功',
            icon: 'success',
            duration: 1500
          });
          
          setTimeout(() => {
            wx.switchTab({
              url: '/pages/workplace/workplace'
            });
          }, 1500);
        }
        else if (auditStatus === 'REJECTED') {
          // 审核拒绝 → 提示重新申请
          wx.showModal({
            title: '入驻申请未通过',
            content: '您的入驻申请未通过审核，请修改申请信息后重新提交。',
            confirmText: '重新申请',
            cancelText: '稍后处理',
            success: (modalRes) => {
              if (modalRes.confirm) {
                wx.redirectTo({
                  url: '/pages/settle/settle'
                });
              }
            }
          });
        }
        else if (auditStatus === 'BANNED') {
          // 账号封禁 → 提示联系客服
          wx.showModal({
            title: '账号已封禁',
            content: '您的账号因违规操作已被封禁，如有疑问请联系平台客服。',
            showCancel: false,
            success: () => {
              // 清除token和用户信息
              wx.removeStorageSync('merchantToken');
              wx.removeStorageSync('merchantUserInfo');
            }
          });
        }
        else {
          // 未知状态，默认提示完善信息
          wx.showToast({
            title: '请先完善入驻信息',
            icon: 'none'
          });
          setTimeout(() => {
            wx.redirectTo({
              url: '/pages/settle/settle'
            });
          }, 2000);
        }
      } else {
        // 登录失败 - 显示具体错误消息
        const errorMsg = response.msg || '登录失败，请重试';
        wx.showToast({
          title: errorMsg,
          icon: 'none',
          duration: 3000
        });
      }
      
      this.setData({ loading: false });
      
    } catch (error: any) {
      this.setData({ loading: false });
      console.error('登录异常:', error);
      
      // 显示详细的错误信息
      let errorMsg = '登录失败，请重试';
      if (error.msg) {
        errorMsg = error.msg;
      } else if (error.errMsg) {
        errorMsg = error.errMsg;
      } else if (typeof error === 'string') {
        errorMsg = error;
      }
      
      wx.showToast({
        title: errorMsg,
        icon: 'none',
        duration: 3000
      });
    }
  },

  /**
   * 商家注册
   */
  async handleRegister() {
    const { registerPhone, smsCode, registerPassword, confirmPassword, agreeProtocol } = this.data;
    
    if (!this.validatePhone(registerPhone)) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      });
      return;
    }
    
    if (!smsCode.trim()) {
      wx.showToast({
        title: '请输入验证码',
        icon: 'none'
      });
      return;
    }
    
    // 密码验证：8-20位，必须包含字母和数字
    if (!registerPassword.trim()) {
      wx.showToast({
        title: '请输入密码',
        icon: 'none'
      });
      return;
    }
    
    if (registerPassword.length < 8 || registerPassword.length > 20) {
      wx.showToast({
        title: '密码长度必须在8-20位之间',
        icon: 'none'
      });
      return;
    }
    
    const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d@$!%*#?&]{8,20}$/;
    if (!passwordRegex.test(registerPassword)) {
      wx.showToast({
        title: '密码必须包含字母和数字',
        icon: 'none'
      });
      return;
    }
    
    if (registerPassword !== confirmPassword) {
      wx.showToast({
        title: '两次密码不一致',
        icon: 'none'
      });
      return;
    }
    
    if (!agreeProtocol) {
      wx.showToast({
        title: '请先同意用户协议',
        icon: 'none'
      });
      return;
    }

    this.setData({ loading: true });

    try {
      // 调用后端API：/merchant/register
      const response = await AuthAPI.merchantRegister({
        phone: registerPhone,
        smsCode: smsCode,
        password: registerPassword,
        confirmPassword: confirmPassword,
        agreeProtocol: agreeProtocol
      });
      
      if (response.code === 200) {
        // 注册成功，不保存token，引导用户登录
        wx.showModal({
          title: '注册成功',
          content: '请使用手机号和密码登录',
          showCancel: false,
          confirmText: '去登录',
          success: (res) => {
            if (res.confirm) {
              // 切换到登录Tab，并自动填充手机号
              this.setData({
                showRegister: false,
                loginPhone: registerPhone  // 自动填充手机号
              });
            }
          }
        });
      } else {
        // 注册失败 - 显示具体错误消息
        const errorMsg = response.msg || '注册失败，请重试';
        wx.showToast({
          title: errorMsg,
          icon: 'none',
          duration: 3000
        });
      }
      
      this.setData({ loading: false });
      
    } catch (error: any) {
      this.setData({ loading: false });
      console.error('注册异常:', error);
      
      // 显示详细的错误信息
      let errorMsg = '注册失败，请重试';
      if (error.msg) {
        errorMsg = error.msg;
      } else if (error.errMsg) {
        errorMsg = error.errMsg;
      } else if (typeof error === 'string') {
        errorMsg = error;
      }
      
      wx.showToast({
        title: errorMsg,
        icon: 'none',
        duration: 3000
      });
    }
  },


  /**
   * 提交商家入驻申请
   */
  async submitMerchantApplication() {
    const { merchantName, merchantType, contactPerson, contactPhone, merchantAddress, agreeProtocol } = this.data;
    
    if (!merchantName.trim()) {
      wx.showToast({
        title: '请输入商家名称',
        icon: 'none'
      });
      return;
    }
    
    if (merchantType === -1) {
      wx.showToast({
        title: '请选择商家类型',
        icon: 'none'
      });
      return;
    }
    
    if (!contactPerson.trim()) {
      wx.showToast({
        title: '请输入联系人姓名',
        icon: 'none'
      });
      return;
    }
    
    if (!this.validatePhone(contactPhone)) {
      wx.showToast({
        title: '请输入正确的联系电话',
        icon: 'none'
      });
      return;
    }
    
    if (!merchantAddress.trim()) {
      wx.showToast({
        title: '请输入商家地址',
        icon: 'none'
      });
      return;
    }
    
    if (!agreeProtocol) {
      wx.showToast({
        title: '请先同意入驻协议',
        icon: 'none'
      });
      return;
    }

    this.setData({ loading: true });

    try {
      // 调用后端API：/merchant/apply
      // const response = await AuthAPI.merchantApply({
      //   merchantName,
      //   merchantType: merchantType + 1, // 1-个体工商户，2-企业
      //   contactPerson,
      //   contactPhone,
      //   address: merchantAddress,
      //   description,
      //   agreedProtocol: agreeProtocol
      // });
      
      // 模拟成功响应
      setTimeout(() => {
        wx.showModal({
          title: '申请提交成功',
          content: '您的入驻申请已提交，我们将在3个工作日内审核并联系您。',
          showCancel: false,
          confirmText: '知道了',
          success: () => {
            this.backToMain();
          }
        });
        
        this.setData({ loading: false });
      }, 800);
      
    } catch (error) {
      this.setData({ loading: false });
      wx.showToast({
        title: '申请提交失败',
        icon: 'none'
      });
    }
  },

  /**
   * 发送短信验证码
   */
  async sendSmsCode() {
    const { registerPhone } = this.data;
    
    if (!this.validatePhone(registerPhone)) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      });
      return;
    }

    try {
      // 调用后端API：/merchant/sms/send
      await AuthAPI.sendSmsCode({
        phone: registerPhone,
        type: 'register'
      });
      
      // 开始倒计时
      this.startSmsCountdown('smsCountdown');
      
      wx.showToast({
        title: '验证码已发送',
        icon: 'success'
      });
      
    } catch (error: any) {
      console.error('发送注册验证码失败:', error);
      
      // 显示详细的错误信息
      let errorMsg = '发送失败，请重试';
      if (error.msg) {
        errorMsg = error.msg;
      } else if (error.errMsg) {
        errorMsg = error.errMsg;
      } else if (typeof error === 'string') {
        errorMsg = error;
      }
      
      wx.showToast({
        title: errorMsg,
        icon: 'none',
        duration: 3000
      });
    }
  },

  /**
   * 发送登录验证码
   */
  async sendLoginSmsCode() {
    const { loginPhone } = this.data;
    
    if (!this.validatePhone(loginPhone)) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      });
      return;
    }

    try {
      // 调用后端API：/merchant/sms/send
      await AuthAPI.sendSmsCode({
        phone: loginPhone,
        type: 'login'
      });
      
      // 开始倒计时
      this.startSmsCountdown('loginSmsCountdown');
      
      wx.showToast({
        title: '验证码已发送',
        icon: 'success'
      });
      
    } catch (error: any) {
      console.error('发送登录验证码失败:', error);
      
      // 显示详细的错误信息
      let errorMsg = '发送失败，请重试';
      if (error.msg) {
        errorMsg = error.msg;
      } else if (error.errMsg) {
        errorMsg = error.errMsg;
      } else if (typeof error === 'string') {
        errorMsg = error;
      }
      
      wx.showToast({
        title: errorMsg,
        icon: 'none',
        duration: 3000
      });
    }
  },


  /**
   * 短信倒计时
   */
  startSmsCountdown(countdownField: string) {
    let countdown = 60;
    this.setData({
      [countdownField]: countdown
    });
    
    const timer = setInterval(() => {
      countdown--;
      if (countdown <= 0) {
        clearInterval(timer);
        this.setData({
          [countdownField]: 0
        });
      } else {
        this.setData({
          [countdownField]: countdown
        });
      }
    }, 1000);
  },

  /**
   * 验证手机号格式
   */
  validatePhone(phone: string): boolean {
    const phoneRegex = /^1[3-9]\d{9}$/;
    return phoneRegex.test(phone);
  },

  /**
   * 查看协议
   */
  viewProtocol(e: any) {
    const type = e.currentTarget.dataset.type;
    wx.showModal({
      title: type === 'agreement' ? '商家入驻协议' : '隐私政策',
      content: '这里是协议内容...',
      showCancel: false
    });
  },

  // 表单输入处理函数
  onLoginPhoneInput(e: any) { this.setData({ loginPhone: e.detail.value }); },
  onPasswordInput(e: any) { this.setData({ password: e.detail.value }); },
  onLoginSmsCodeInput(e: any) { this.setData({ loginSmsCode: e.detail.value }); },
  onRegisterPhoneInput(e: any) { this.setData({ registerPhone: e.detail.value }); },
  onSmsCodeInput(e: any) { this.setData({ smsCode: e.detail.value }); },
  onRegisterPasswordInput(e: any) { this.setData({ registerPassword: e.detail.value }); },
  onConfirmPasswordInput(e: any) { this.setData({ confirmPassword: e.detail.value }); },
  
  onMerchantNameInput(e: any) { this.setData({ merchantName: e.detail.value }); },
  onContactPersonInput(e: any) { this.setData({ contactPerson: e.detail.value }); },
  onContactPhoneInput(e: any) { this.setData({ contactPhone: e.detail.value }); },
  onMerchantAddressInput(e: any) { this.setData({ merchantAddress: e.detail.value }); },
  onDescriptionInput(e: any) { this.setData({ description: e.detail.value }); },
  
  togglePassword() {
    this.setData({
      showPassword: !this.data.showPassword
    });
  },

  toggleRegisterPassword() {
    this.setData({
      showRegisterPassword: !this.data.showRegisterPassword
    });
  },

  onMerchantTypeChange(e: any) {
    this.setData({
      merchantType: parseInt(e.detail.value)
    });
  },

  onAgreeProtocolChange(e: any) {
    this.setData({
      agreeProtocol: e.detail.value.includes('agree')
    });
  },

  onRememberPasswordChange(e: any) {
    this.setData({
      rememberPassword: e.detail.value.includes('remember')
    });
  }
});
